package com.herui.sdyu_lib.base;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;


import com.herui.sdyu_lib.R;
import com.herui.sdyu_lib.base.fragment.Fragmentation;
import com.herui.sdyu_lib.utils.LogUtils;

import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;


public abstract class BaseActivity extends FragmentActivity {
    public String TAG = "BaseFragment";

    private boolean debug = true;

    private boolean isCreate;
//    private BaseFragment currentFragment;

    protected Fragmentation fragmentation;

    protected long recordTime;

    public Fragmentation getFragmentation() {
        return fragmentation;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (debug)
            LogUtils.i(getLocalClassName() + "  onCreate");

        if (!showTitle())
            requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏标题

        ViewGroup group = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.stf_template, null);
        LayoutInflater.from(this).inflate(getLayout(), group, true);
        setContentView(group);

        isCreate = true;

        fragmentation = new Fragmentation(getSupportFragmentManager(), getContent());
        BaseAppcation.getInstance().addActivity(this);

        onHandleSaveInstancState(savedInstanceState);
    }

    protected void setStatusBarColor(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(color);
        }
    }

    protected void hideNavigationBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(option);
        }
    }

    protected void onHandleSaveInstancState(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            List<Fragment> fragments = getSupportFragmentManager().getFragments();

            if (fragments != null && fragments.size() > 0) {
                boolean showFlag = false;

                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                for (int i = fragments.size() - 1; i >= 0; i--) {
                    Fragment fragment = fragments.get(i);
                    if (fragment != null) {
                        if (!showFlag) {
                            ft.show(fragments.get(i));
                            showFlag = true;
                        } else {
                            ft.hide(fragments.get(i));
                        }
                    }
                }
                ft.commit();
            }
        }
    }

    @Override
    public void onBackPressed() {
        LogUtils.i("onBackPressed:" + getClass().getName());
        BaseFragment topFragment = getTopFragment();
        if (topFragment != null) {
            boolean result = topFragment.onBackPressedSupport();
            if (result) {
                return;
            }
        }

        // 当回退栈中fragment数量两个或者以上的时候 调用默认的回退
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            super.onBackPressed();
        } else {
            int index = 0;
            if (getSupportFragmentManager().getFragments() != null) {
                for (Fragment fragment : getSupportFragmentManager().getFragments()) {
                    if (fragment != null) {
                        index++;
                    }
                }
            }
            // 当回退栈中fragment数量为1的话 查看是否只有一个fragment，如果是的话直接finish，防止出现白屏
            // 当回退栈中fragment数量为0的话 也直接finish
            if (index <= 1)
                finish();
            else
                super.onBackPressed();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (debug)
            LogUtils.i(getLocalClassName() + "  onResume");

        if (isCreate) {
            isCreate = false;
            initParam();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (debug)
            LogUtils.i(getLocalClassName() + "  onPause");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (debug)
            LogUtils.i(getLocalClassName() + "  onDestroy");

        BaseAppcation.getInstance().delActivity(this);
    }

    public void jump(Class<?> cls){
        jump(new Intent(this, cls));
    }

    public void jump(Intent intent){
        startActivity(intent);
    }

    public void jumpAndFinish(Class<?> cls){
        startActivity(new Intent(this, cls));
        finish();
    }

    /**
     * 替换fragment
     *
     * @param constantID
     * @param fragment
     * @param fragmentTag
     * @param saveBack
     */
    @Deprecated
    public void replace(int constantID, BaseFragment fragment, String fragmentTag,
                        boolean saveBack, FragmentDirectionAnim anim) {
        // 开启Fragment事务
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        String toName = fragment.getClass().getName();
        if (anim != null)
            ft.setCustomAnimations(anim.enterAnim, anim.exitAnim);
        else
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        ft.replace(constantID, fragment, toName);
        if (saveBack)
            ft.addToBackStack(toName);
        ft.commit();
    }

    @Deprecated
    public void replace(BaseFragment fragment, String fragmentTag, boolean saveBack,
                        FragmentDirectionAnim fragmentDirectionAnim) {
        replace(getContent(), fragment, fragmentTag, saveBack, fragmentDirectionAnim);
    }

    protected void removeFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().remove(fragment).commit();
    }

    /**
     * 显示和隐藏
     *
     * @param from
     * @param to
     * @param removeFrom
     */
    public void switchContent(BaseFragment from, BaseFragment to, boolean removeFrom,
                              FragmentDirectionAnim fragmentDirectionAnim) {
        switchContent(getContent(), from, to, removeFrom, fragmentDirectionAnim);
    }

    /**
     * 显示和隐藏
     *
     * @param constantID
     * @param from
     * @param to
     * @param removeFrom
     * @param anim
     */
    public void switchContent(int constantID, BaseFragment from, BaseFragment to, boolean
            removeFrom,
                              FragmentDirectionAnim anim) {

        fragmentation.switchBrotherFragment(from, to, anim);
    }

    /**
     * 获取栈内的framgent对象
     *
     * @param fragmentClass
     */
    public <T extends BaseFragment> T findFragment(Class<T> fragmentClass) {
        return fragmentation.findStackFragment(fragmentClass, getSupportFragmentManager());
    }

    /**
     * 出栈
     */
    public void pop() {
        fragmentation.back(getSupportFragmentManager());
    }

    /**
     * 出栈到目标fragment
     *
     * @param fragmentClass 目标fragment
     * @param includeSelf   是否包含该fragment
     */
    public void popTo(Class<?> fragmentClass, boolean includeSelf) {
        fragmentation.popTo(fragmentClass, includeSelf, getSupportFragmentManager());
    }

    /**
     * 用于出栈后,立刻进行FragmentTransaction操作
     */
    public void popTo(Class<?> fragmentClass, boolean includeSelf, Runnable
            afterPopTransactionRunnable) {
        fragmentation.popTo(fragmentClass, includeSelf, getSupportFragmentManager());
    }

    /**
     * replace
     *
     * @param to
     * @param saveBack 是否保留到栈
     */
    public void replace(Fragment to, boolean saveBack, FragmentDirectionAnim anim) {
        fragmentation.replace(to, saveBack, anim);
    }

    /**
     * 添加并隐藏当前的
     *
     * @param to
     */
    public void add(BaseFragment to, FragmentDirectionAnim anim) {
        if (System.currentTimeMillis() - recordTime > 500) {
            fragmentation.add(getTopFragment(), to, anim);
            recordTime = System.currentTimeMillis();
        }
    }

    /**
     * 添加并删除当前的
     *
     * @param to
     */
    public void addWithFinish(BaseFragment to, FragmentDirectionAnim anim) {
        fragmentation.addWithFinish(getTopFragment(), to, anim);
    }


    /**
     * 得到位于栈顶Fragment 该方法是从栈中把fragment拿出来，所以必须放在回退栈中
     *
     * @return
     */
    public BaseFragment getTopFragment() {
        return fragmentation.getTopFragment(getSupportFragmentManager());
    }

    /**
     * 打印该activity下的所有fragment
     */
    public void printAllFragment() {
        LogUtils.i("----------printAllFragment--------------");
        for (Fragment fragment : getSupportFragmentManager().getFragments()) {
            if (fragment != null) {
                LogUtils.i(fragment.getClass().getName());
                if (fragment.getChildFragmentManager().getFragments() != null)
                    for (Fragment fragment1 : fragment.getChildFragmentManager()
                            .getFragments()) {
                        if (fragment1 != null)
                            printAllFragment(fragment1, 1);
                    }
            } else
                LogUtils.i("null");
        }
    }

    private void printAllFragment(Fragment fragment, int deep) {

        if (fragment.getChildFragmentManager().getFragments() != null && fragment
                .getChildFragmentManager().getFragments().size() > 0) {
            for (Fragment fragment1 : fragment.getChildFragmentManager()
                    .getFragments()) {
                if (fragment1 != null) {
                    StringBuilder head = new StringBuilder();
                    for (int i = 0; i < deep; ++i)
                        head.append("-");
                    LogUtils.i(head.toString() + fragment1.getClass().getName());

                    printAllFragment(fragment1, ++deep);
                } else {
                    StringBuilder head = new StringBuilder();
                    for (int i = 0; i < deep; ++i)
                        head.append("-");
                    LogUtils.i(head.toString() + "null");
                }
            }
        } else {
            StringBuilder head = new StringBuilder();
            for (int i = 0; i < deep; ++i)
                head.append("-");
            LogUtils.i(head.toString() + fragment.getClass().getName());
        }
    }

    /**
     * 打印栈fragment
     */
    public void printStackFragments() {
        int count = getSupportFragmentManager().getBackStackEntryCount();
        LogUtils.i("----------printStackFragments--------------count:" + count);

        for (int i = 0; i < count; i++) {
            String tag = getSupportFragmentManager().getBackStackEntryAt(i).getName();
            Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
            if (fragment != null) {
                StringBuilder head = new StringBuilder();
                for (int j = 0; j < i; ++j)
                    head.append("-");
                LogUtils.i(head.toString() + fragment.getClass().getName());

                printStackFragments(fragment);
            }
        }
    }

    private void printStackFragments(Fragment fragment) {
        int count = fragment.getChildFragmentManager().getBackStackEntryCount();
        LogUtils.i("count:" + count);

        for (int i = 0; i < count; i++) {
            String tag = fragment.getChildFragmentManager().getBackStackEntryAt(i).getName();
            Fragment fragment1 = fragment.getChildFragmentManager().findFragmentByTag(tag);
            if (fragment1 != null) {
                StringBuilder head = new StringBuilder();
                for (int j = 0; j < i; ++j)
                    head.append("-");
                LogUtils.i(head.toString() + fragment1.getClass().getName());

                printStackFragments(fragment1);
            } else {
                StringBuilder head = new StringBuilder();
                for (int j = 0; j < i; ++j)
                    head.append("-");
                LogUtils.i(head.toString() + "null");
            }
        }
    }


    public int getContent() {
        return 0;
    }

    public boolean showTitle() {
        return false;
    }

    public abstract int getLayout();

    public abstract void initParam();

}
